<?php

namespace app\home\controller;

use \think\Db;

class Data
{
	
	public function __construct()
	{

		require_once EXTEND_PATH . 'PHPExcel/PHPExcel.php';
		require_once EXTEND_PATH . 'PHPExcel/PHPExcel/IOFactory.php';
		$this->Key = [];
		foreach(range('A', 'Z') as $val){
			$this->Key[] = $val;
		}

	}

	public function areas()
	{
		$list = Db::name('area')->where('level', '=', '1')->select();
		foreach($list as $val) {
			echo '        '.$val['area_code'].': "'.$val['area_name'].'",';
			echo "\r\n";
		}
	}

	public function area()
	{

		$Excel = new \PHPExcel();
		$Reader = new \PHPExcel_Reader_Excel5();
		$Excel = $Reader->load(_DATA_ . 'data_area.xls');
		$Sheet = $Excel->getSheet(0);
		$allRow = $Sheet->getHighestRow();
		$allColumn = $Sheet->getHighestColumn();
		$dd_list = array();
		for($r = 2; $r<=$allRow; $r++) {
			for($c='A'; $c<=$allColumn; $c++) {
				$address = $c.$r;
				$dd_val = trim((string)$Sheet->getCell($address)->getValue());
				$dd_val = str_replace('中国', '', $dd_val);
				$dd_val = preg_replace('/^,+/', '', $dd_val);
				$dd_list[$r][$c] = $dd_val;
			}
		}
		print_r($dd_list);
		$cur_level = 0;
		foreach($dd_list as $val) {
			$tmp_arr = explode(',', $val['B']);
			if(in_array($tmp_arr[0], ['北京市', '天津市', '上海市', '重庆市', '香港特别行政区', '澳门特别行政区'])) {
				if(count($tmp_arr) == 1) {
					$id = Db::name('area')->insertGetId([
						'pid' => 0,
						'level' => 1,
						'area_code' => $val['A'],
						'area_name' => end($tmp_arr),
					]);
					$id = Db::name('area')->insertGetId([
						'pid' => $id,
						'level' => 2,
						'area_code' => $val['A'] + 100,
						'area_name' => end($tmp_arr),
					]);
				} else {
					Db::name('area')->insertGetId([
						'pid' => $id,
						'level' => 3,
						'area_code' => $val['A'],
						'area_name' => end($tmp_arr),
					]);
				}
			} else {
				$level = count($tmp_arr);
				if($level == 1) {
					$id = Db::name('area')->insertGetId([
						'pid' => 0,
						'level' => $level,
						'area_code' => $val['A'],
						'area_name' => end($tmp_arr),
					]);
				} else {
					if($level != $cur_level) {
						$cur_level = $level;
						$id = Db::name('area')->insertGetId([
							'pid' => $id,
							'level' => $level,
							'area_code' => $val['A'],
							'area_name' => end($tmp_arr),
						]);
					} else {
						Db::name('area')->insertGetId([
							'pid' => $id,
							'level' => $level,
							'area_code' => $val['A'],
							'area_name' => end($tmp_arr),
						]);
					}
				}
			}
		}

	}

}

